
import { Component, OnInit, OnDestroy, AfterViewInit, Input } from '@angular/core';
import { DynamicDialogConfig } from 'primeng/primeng';
import { CommonService } from 'app/common/service/common.service';

@Component({
    selector: 'qk-media',
    templateUrl: './qkmedia.component.html',
    styleUrls: ['./qkmedia.component.scss'],
    providers: [CommonService]
})
export class QkMediaComponent implements OnInit, OnDestroy {
    medias: any[];
    currentIndex: number = 0;
    currentMedia: any;
    videoPlayers: any[] = [];

    id: number;
    constructor(
        private commonService: CommonService,
        private config: DynamicDialogConfig) {
        this.id = config.data.id;
    }

    ngOnInit() {
        this.medias = [];
        this.commonService.loadMediaDetail(this.id).subscribe(data => {
            let media = data.media;
            this.medias.push({ id: media.mediaId, src: media.mediaPath, type: media.mediaType });
            if (media.mediaType == "MP4") {
                setTimeout(() => {
                    let videoPlayer = videojs('qk-video-' + media.mediaId);
                    videoPlayer.ready(function () {
                        var obj = this;
                        obj.src([{ type: "video/mp4", src: media.mediaPath }]);
                        obj.load();
                    });
                    this.videoPlayers.push(videoPlayer)
                }, 200);
            } else if (media.mediaType == "DOC" || media.mediaType == "DOCX") {
                setTimeout(() => {
                    var pdfData = atob(data.content); //$.base64.
                    var uint8Array = new Uint8Array(pdfData.length);
                    for (var i = 0; i < pdfData.length; i++) {
                        uint8Array[i] = pdfData.charCodeAt(i);
                    }
                    window['printPdfContent'] = { 'pdfName': media.mediaName, 'pdfContent': uint8Array };
                    $("#pdfConcent").attr("src", "/assets/other/pdfjs/viewer.html").ready();
                    $("#pdfConcent").show();
                }, 200);
            }
        });
        this.currentMedia = this.medias[this.currentIndex];
    }

    ngOnDestroy() {
        this.videoPlayers.forEach(player => player.dispose());
    }

    stopCurrentVideo() {
        if (this.currentMedia && this.currentMedia.type == 'video') {
            let videoPlayer = videojs('video-' + this.currentMedia.id);
            videoPlayer.reset();
            videoPlayer.src([{ type: "video/mp4", src: this.currentMedia.src }]);
            videoPlayer.load();
        }
    }
}

